const Service = require('egg').Service;
const { error, success } = require('../utils/response.js')
const moment = require('moment')

class CommentService extends Service {
    // 获取评论 分页
    async getPage(info, ctx) {
        const limit = info.limit || 10;
        const page = info.page || 1;
        const {invId} = info;
        const res = await this.app.mysql.query(`select * from user u,comment c where c.invId=? and u.id=c.userId order by createTime desc limit ? offset ?`, [invId,limit * page, (page - 1) * limit]);
        // 获取总页数
        const resTotal = await this.app.mysql.query(`select count(id) from comment where invId=?`,[invId]);
        const totalPage = Math.ceil(resTotal[0]['count(id)'] / limit);
        res.forEach(element => {
            delete element.password
            element.createTime = moment(Number(element.createTime)).format('YYYY-MM-DD HH:mm:ss');
        });
        success(ctx, '获取成功',{totalPage,currentPage:Number(page),total: resTotal[0]['count(id)'],data:res})
    }

    // 添加评论功能  需要登录权限
    async add(info, ctx) {
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        const now = moment().valueOf();
        const res = await this.app.mysql.insert('comment',{...info,userId:userInfo.id,createTime:now})
        if (res.affectedRows !== 1) error(ctx, '添加评论失败！请检查后台服务')
        success(ctx, '添加成功！')
    }
    // 删除评论功能  需要登录权限
    async delete(info, ctx) {
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        if (userInfo.status === 0) return error(ctx, '没有该接口的权限')
        const {id} = info
        const res = await this.app.mysql.delete('comment',{id});
        if(res.affectedRows !== 1) error(ctx, '删除评论失败！请检查后台服务')
        success(ctx, '删除成功')
    }
}
module.exports = CommentService;